#!/bin/bash

. script/bootstrap

setup_mysql() {
  if [ ! -f "dbdeployer" ] ; then
    return
  fi
  ./dbdeployer deploy single "5.7.21" --sandbox-binary $PWD/sandbox/binary --sandbox-home $PWD/sandboxes --sandbox-directory orc-sandbox --port=3306
  mkdir -p bin
  ln -s /go/src/github.com/github/orchestrator/sandboxes/orc-sandbox/use bin/mysql
  chmod +x bin/mysql
  PATH=bin:$PATH
}

setup_mysql

echo "# Validating documentation"
echo "## docs/toc.md and docs/README.md must be identical"
diff docs/toc.md docs/README.md > /dev/null 2> /dev/null

echo "## Checking if all local links are backed by doc files"
egrep -R '[(][^/()]+.md[)]' docs/ -o --no-file | sort | uniq | tr -d '()' | while read link ; do
  echo "### Checking link: $link"
  ls docs/$link > /dev/null && echo "## - yes" || exit 1
done

echo "## Checking every doc page has an inbound link"
ls docs/*.md | grep -v README.md | while read f ; do
  docfile="$(basename $f)"
  echo "### Checking if doc file $docfile is linked from another doc"
  egrep -c -R "[(]$docfile[)]" docs/ -q && echo "## - yes" || exit 1
done

echo "# Verifying code is formatted via 'gofmt -s -w  go/'"
gofmt -s -w  go/
git diff --exit-code --quiet go/

echo "# Building"
script/build

cd .gopath/src/github.com/github/orchestrator

echo "# Running unit tests"
go test ./go/...

echo "# Running integration tests"
./tests/integration/test.sh || exit 1

echo "# Done"
